const { regClass, property } = Laya;
import PhysicsGameMainRT from "../scence/physicsDemo/PhysicsGameMainRT";
/**
 * 掉落盒子脚本，实现盒子碰撞及回收流程
 */
@regClass()
export default class DropBox extends Laya.Script {

    /**盒子爆炸动画的预制体 */
    @property({ type: Laya.Prefab, caption: "爆炸动画" })
    private burstAni: Laya.Prefab;
    /**等级文本对象引用 */
    private _text: Laya.Text;
    /**盒子等级 */
    private _level: number;

    constructor() { super(); }
    onEnable(): void {
        this._level = Math.round(Math.random() * 5) + 1;
        this._text = this.owner.getChildByName("levelTxt") as Laya.Text;
        this._text.text = this._level + "";

    }

    onUpdate(): void {
        //让持续盒子旋转
        (this.owner as Laya.Sprite).rotation++;
    }

    onTriggerEnter(other: any): void {
        var owner: Laya.Sprite = this.owner as Laya.Sprite;
        if (other.label === "buttle") {
            //碰撞到子弹后，增加积分，播放声音特效
            if (this._level > 1) {
                this._level--;
                this._text.text = (this._level + "");
                owner.getComponent(Laya.RigidBody).setVelocity({ x: 0, y: -10 });
                Laya.SoundManager.playSound("resources/sound/hit.wav");
            } else {
                if (owner.parent) {
                    let effect: Laya.Sprite = Laya.Pool.getItemByCreateFun("effect", this.createEffect, this);
                    owner.parent.addChild(effect);//将爆炸动画添加到父节点中
                    effect.pos(owner.x, owner.y);//设置爆炸动画的位置，让其跟随方块
                    owner.removeSelf();//删除方块自身节点对象
                    Laya.SoundManager.playSound("resources/sound/destroy.wav");
                }
            }

            PhysicsGameMainRT.instance.addScore(1);
        } else if (other.label === "ground") {
            //只要有一个盒子碰到地板，则停止游戏
            owner.removeSelf();
            PhysicsGameMainRT.instance.stopGame();
        }
    }

    /**使用对象池创建爆炸动画 */
    createEffect(): Laya.Sprite {
        //获取动画预制体的节点对象
        const aniNode: Laya.Sprite = this.burstAni.create() as Laya.Sprite;
        const ani: Laya.Animator2D = aniNode.getComponent(Laya.Animator2D);//获取动画组件对象
        //帧听默认状态机上的动画播放事件，在动画播放完毕后，删除节点对象并回收到对象池中。 
        ani.getControllerLayer().defaultState.on(Laya.AnimatorState2D.EVENT_OnStateExit, () => {
            aniNode.removeSelf();//删除动画节点
            Laya.Pool.recover("effect", aniNode);//回收动画预制体到对象池中，方便下次复用。
        });
        return aniNode;
    }

    onDisable(): void {
        //盒子被移除时，回收盒子到对象池，方便下次复用，减少对象创建开销。
        Laya.Pool.recover("dropBox", this.owner);
    }
}